package cn.eeepay.boss.thread;

import cn.eeepay.framework.dao.UserCouponDao;
import cn.eeepay.framework.model.UserCoupon;
import cn.eeepay.framework.service.impl.SensorsService;
import cn.eeepay.framework.util.DateUtil;
import cn.eeepay.framework.util.ThreadFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;

/**
 * 优惠券过期处理
 */
public class UserCouponRunnable implements Runnable {

    private static final Logger log = LoggerFactory.getLogger(UserCouponRunnable.class);

    private Long minId;
    private Long maxId;
    private CountDownLatch countDownLatch;
    private UserCouponDao userCouponDao;
    private SensorsService sensorsService;
    private Map couponCodeMap;

    public UserCouponRunnable(Long minId, Long maxId, CountDownLatch countDownLatch,
                              UserCouponDao userCouponDao, SensorsService sensorsService,
                              Map couponCodeMap) {
        this.minId = minId;
        this.maxId = maxId;
        this.countDownLatch = countDownLatch;
        this.userCouponDao = userCouponDao;
        this.sensorsService = sensorsService;
        this.couponCodeMap = couponCodeMap;
    }

    @Override
    public void run() {
        try {
            log.info("异步处理过期优惠券,minId:{},maxId:{}", minId, maxId);
            dealWith();
        } catch (Exception e) {
            log.error("异步过期优惠券异常", e);
        } finally {
            countDownLatch.countDown();
        }
    }

    /**
     * 处理过期优惠券
     */
    private void dealWith() {
        int pageNo = 0;
        int pageSize = 300;
        while (true) {
            List<UserCoupon> expCoupons = userCouponDao.queryExpCouponsInMinMax(minId, maxId, pageNo * pageSize, pageSize);
            if(expCoupons == null || expCoupons.isEmpty()) {
                break;
            }
            List<UserCoupon> insertCoupons=new ArrayList<>();
            String order = DateUtil.getMessageTextTime();
            for(int i = 0; i < expCoupons.size(); i ++){
                String couponCode = expCoupons.get(i).getCouponCode();
                if("3".equals(couponCode) || "6".equals(couponCode)){
                    UserCoupon userCoupon=expCoupons.get(i);
                    userCoupon.setToken("EXP"+order+i);
                    userCoupon.setCouponStatus("0");
                    userCoupon.setCancelVerificationType("3");
                    insertCoupons.add(userCoupon);
                }
                try {
                    sensorsService.invalidCoupon(expCoupons.get(i), couponCodeMap);
                } catch (Exception e) {
                    log.error("调用神策异常", e);
                }
            }
            //过期充值返数据写入核销表
            if(insertCoupons != null && insertCoupons.size() > 0){
                userCouponDao.batchInsertexpCoupon(insertCoupons);
            }
            pageNo++;
        }
    }
}
